<template>
	<view class="card">
		<view 
			class="craditem" 
			v-for="(item,index) in newCheckOptions" 
			:key="index" 
			:class="{'active': item.selected}"
			:style="{ '--color': activeColor }" 
			@click="selectData(index,item)"
		>
			{{item.name}}
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			//选项数据
			checkOptions: {
				type: Array,
				default () {
					return []
				}
			},
			//选择类型(单选：single，默认复选)
			checkType: {
				type: String,
				default: ''
			},
			//复选时最大可选数量(类型为单选的时不生效)
			maxNum: {
				type: Number,
			},
			//主题色
			activeColor: {
				type: String,
				default: '#0A4B9D'
			}
		},
		watch: {
			checkOptions: {
				deep: true,
				immediate: true,
				handler(parentArry) {
					this.newCheckOptions = parentArry
				},
			}
		},
		data() {
			return {
				newCheckOptions: []
			}
		},
		methods: {
			selectData(index, item) { 
				//单选
				if (this.checkType === 'single') {
					if(item.selected && !item.isUnrestricted) return
					this.newCheckOptions.forEach(mess => {
						mess.selected = false
					})
					this.$set(item, 'selected', true)
				} else {
					let chooseData = this.newCheckOptions.filter(mes => mes.selected)
					if (this.maxNum && !item.selected && chooseData.length >= this.maxNum) {
						uni.showToast({
							title: '最多可选' + this.maxNum + '项',
							icon: 'none'
						})
						return
					}
					this.$set(item, 'selected', item.selected ? false : true)
				}
				this.newCheckOptions = JSON.parse(JSON.stringify(this.newCheckOptions))
				let chooseOnData = this.newCheckOptions.filter(mes => mes.selected)
				this.$emit("update:checkOptions", this.newCheckOptions)
				this.$emit("checkChange", chooseOnData)
			},
			//重置
			reset() {
				this.newCheckOptions.forEach(mess => {
					mess.selected = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.card {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		flex-wrap: wrap;
		.craditem {
			padding: 8rpx 14rpx;
			margin-right: 10rpx;
			margin-bottom: 10rpx;
			background: #FFFFFF;
			border-radius: 8rpx;
			border: 2rpx solid #999999;
			font-size: 28rpx;
			font-weight: 400;
			color: #333333;
		}
		.active {
			border: 2rpx solid var(--color);
			color: var(--color);
			position: relative;
		}
		
		.active::after {
			content: "";
			position: absolute;
			top: 0;
			right: 0;
			width: 0;
			height: 0;
			border-top: 32rpx solid var(--color);
			border-left: 32rpx solid transparent;
		}
		
		.active::before {
			width: 6rpx;
			height: 10rpx;
			border-color: #FFFFFF;
			border-style: solid;
			border-width: 0 1rpx 2rpx 0;
			content: "";
			position: absolute;
			right: 5rpx;
			top: 2rpx;
			z-index: 3;
			transform: rotate(45deg);
		}
	}
</style>